package cn.exrick.xboot.config.Json;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import de.codecentric.boot.admin.server.domain.values.Registration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 忽略未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SimpleModule numberModule = new SimpleModule();
        // 将 Long 类型序列化为字符串
        numberModule.addSerializer(Long.class, ToStringSerializer.instance);
        numberModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(numberModule);

        JavaTimeModule module = new JavaTimeModule();
        // 全局配置 LocalDateTime 的格式化
        module.addSerializer(LocalDateTime.class, new com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer(
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
        ));
        objectMapper.registerModule(module);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 禁用时间戳格式


        // 处理 Registration 类型的反序列化
        SimpleModule registrationModule = new SimpleModule();
        registrationModule.addDeserializer(Registration.class, new JsonDeserializer<Registration>() {
            @Override
            public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
                JsonNode node = p.getCodec().readTree(p);
                String name = node.get("name").asText();
                String url = node.get("url").asText();
                return null;
            }
        });
        objectMapper.registerModule(registrationModule);

        return objectMapper;
    }
}